import useCurrentUser from "@/app/utils/hooks/useCurrentUser"
import { useFavorites } from "@/app/utils/hooks/useFavorites"
import axios from "axios"
import { useCallback, useMemo } from "react"
import { AiOutlineCheck, AiOutlinePlus } from "react-icons/ai"

interface FavoriteButtonProps {
    movieId: string,
}

export const FavoriteButton = ({ movieId }: FavoriteButtonProps) => {
    const { mutate: mutateFavorites } = useFavorites()
    const { data: currentUser, mutate } = useCurrentUser()
    // 作用是 判断当前用户是否已经收藏了该电影
    const isFavorite = useMemo(() => {
        return currentUser?.favoriteIds?.includes(movieId)
    }, [currentUser, movieId])
    const toggleFavorites = useCallback(async () => {
        let response
        if (isFavorite) {
            response = await axios.delete("/api/favorite", { data: { movieId } })
        } else {
            response = await axios.post("/api/favorite", { movieId })
        }
        const updatedFavorites = response.data.data.favoriteIds
        // 数据缓存
        mutate({
            ...currentUser,
            favoriteIds: updatedFavorites
        })
        // 数据缓存
        mutateFavorites()

    }, [movieId, isFavorite, mutate, mutateFavorites, currentUser])
    const Icon = isFavorite ? AiOutlineCheck : AiOutlinePlus

    return (<div onClick={toggleFavorites} className="cursor-pointer group/item w-6 h-6 lg:w-10 lg:h-10 border-white border-2 rounded-full flex justify-center items-center transition hover:border-neutral-300 ">
        <Icon className="text-white" size={20} />

    </div>)
}